<?php

namespace App\Http\Controllers;

use App\Transformers\BaseTransformer;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Http\JsonResponse;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Routing\Controller as BaseController;
use League\Fractal\Manager;
use League\Fractal\Pagination\IlluminatePaginatorAdapter;
use League\Fractal\Resource\Collection;
use League\Fractal\Resource\Item;


class DreamerController extends BaseController
{
    use AuthorizesRequests, ValidatesRequests;

    public function noContent() : JsonResponse
    {
        return response()->json([], 204);
    }

    public function responseArray($object) : JsonResponse
    {
        return response()->json($object);
    }

    public function responseItem($object, BaseTransformer $Transformer) : JsonResponse
    {
        $response = (new Manager())
            ->createData(new Item($object, $Transformer))
            ->toArray();

        return response()->json($response['data'], 200);
    }

    public function responseCollection($object, BaseTransformer $Transformer, array $meta = []) : JsonResponse
    {
        $resource = (new Collection($object, $Transformer))->setMeta($meta);

        $response = (new Manager())->createData($resource)->toArray();

        return response()->json($response, 200);
    }

    public function responsePaginate(LengthAwarePaginator $paginator, BaseTransformer $transformer, array $meta = []) : JsonResponse
    {
        $resource = (new Collection($paginator->getCollection(), $transformer))
            ->setPaginator(new IlluminatePaginatorAdapter($paginator))
            ->setMeta($meta);

        $response = (new Manager())->createData($resource)->toArray();

        return response()->json($response, 200);
    }

    public function validateWithArray(
        array $request, array $rules, array $messages = [], array $customAttributes = []
    ) {
        return $this->getValidationFactory()->make(
            $request, $rules, $messages, $customAttributes
        )->validate();
    }

}
